<?php
declare(strict_types=1);

namespace App\Controller;

use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Swoole\Http\Request;
use Swoole\Server;
use Swoole\Websocket\Frame;
use Swoole\WebSocket\Server as WebSocketServer;
use App\Logic\Aes;
use App\Model\TmpMessage;
use App\Model\GroupChatAccess;
use App\Model\GroupChatMsg;
use App\Model\User;

class WebSocketController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    public function onMessage($server, Frame $frame): void
    {
        $tmpid = Aes::decrypt($frame->data);
        if ($tmpid) {
            $onMessage = TmpMessage::query()->find($tmpid);
            if($onMessage){
                $fd = $this->setFd($frame->fd, $onMessage->uid, $onMessage->gid);
                if($onMessage->gid){
                    $users = GroupChatAccess::query()->where('gid', $onMessage->gid)->get();
                    
                    if ($onMessage->message == '#1##@@@@！#27941662####') {
                        $onMessage->message = str_replace('{author}', $onMessage->username, '"{author}" 进入了聊天室');
                        $onMessage->username = '系统消息';
                    }else{
                        // 写入消息记录
                        $GroupChatMsg = new GroupChatMsg();
                        $GroupChatMsg->uid = $onMessage->uid;
                        $GroupChatMsg->username = $onMessage->username;
                        $GroupChatMsg->message = $onMessage->message;
                        $GroupChatMsg->gid = $onMessage->gid;
                        $GroupChatMsg->dateline = time();
                        $GroupChatMsg->save();
                    }
                    
                    $message = [
                        'author'   =>  $onMessage->username,
                        'message'   =>  $onMessage->message,
                        'dateline'  =>  date('Y-m-d H:i:s', time())
                    ];
                    
                    foreach ($users as $user){
                        $server->push($user->fd, json_encode($message));
                    }
                }
                $onMessage->delete();
            }
        }
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        $user = GroupChatAccess::query()->where('fd', $fd)->first();
        if($user){
            if($user->gid){
                $gid = $user->gid;
                $uid = $user->uid;
                GroupChatAccess::query()->where('fd', $fd)->delete();
                $users = GroupChatAccess::query()->where('gid', $gid)->get();
                $user = User::query()->find($uid);
                if($user){
                    $author = $user->username;
                }
                $message = [
                    'author'    =>  '系统消息',
                    'message'   =>  str_replace('{author}', $author, '"{author}" 离开了聊天室'),
                    'dateline'  =>  date('Y-m-d H:i:s', time())
                ];
                foreach ($users as $user){
                    $server->push($user->fd, json_encode($message));
                }
            }
        }
    }

    public function onOpen($server, Request $request): void
    {
        // $server->push($request->fd, '欢迎来到'.$request->fd);
    }
    
    public function setFd($fd, $uid, $gid=0){
        $access = GroupChatAccess::query()->where('fd', $fd)->first();
        if(!$access){
            $access = new GroupChatAccess();
        }
        $access->fd = $fd;
        $access->uid = $uid;
        $access->gid = $gid;
        $access->dateline = time();
        $access->save();
        return $fd;
    }
}